package cn.sciento.farm.devicemanager.gateway.model.downlink;

import cn.sciento.farm.devicemanager.common.constant.LoraWanConstant;
import cn.sciento.farm.devicemanager.gateway.model.lorawan.DeviceTx;
import com.alibaba.fastjson.JSON;
import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.Base64;

@Data
public class LoraWanConfigData implements MqttEncoder {

    Logger logger = LoggerFactory.getLogger(getClass());

    private String concentrator;
    private Short period;
    private Short responseTime;


    @Override
    public MqttContent generate() {
        MqttContent mqttContent = new MqttContent();
        String topic = String.format(LoraWanConstant.DOWNLINK_TOPIC_TEMPLATE,
                LoraWanConstant.APPLICATION_ID,
                concentrator
        );
        DeviceTx deviceTx = new DeviceTx();
        deviceTx.setDevEUI(concentrator);
        String data = Base64.getEncoder().encodeToString(generateData());
        deviceTx.setData(data);
        deviceTx.setConfirmed(true);
        mqttContent.setTopic(topic);
        mqttContent.setPayload(JSON.toJSONString(deviceTx));
        return mqttContent;
    }

    private byte[] generateData(){
        ByteBuffer buffer = ByteBuffer.allocate(10);
        if(period != null){
            buffer.put((byte) 0);
            buffer.putShort(period);
        }
        if(responseTime != null){
            buffer.put((byte) 1);
            buffer.putShort(responseTime);
        }
        buffer.flip();
        byte[] b = conver(buffer);

        logger.info("lorawan配置数据是： {}",Arrays.toString(b));
        return b;

    }

    //必须调用完后flip()才可以调用此方法
    private static byte[] conver(ByteBuffer byteBuffer){
        int len = byteBuffer.limit() - byteBuffer.position();
        byte[] bytes = new byte[len];

        if(byteBuffer.isReadOnly()){
            return null;
        }else {
            byteBuffer.get(bytes);
        }
        return bytes;
    }
}
